package com.source.hotelbath.net;

import android.app.Activity;
import android.content.Context;
import android.system.ErrnoException;
import android.text.TextUtils;
import android.util.Log;

import com.ffcs.network.connect.CustomerError;
import com.ffcs.network.connect.ResponseListener;
import com.ffcs.network.connect.okhttp.client.OkRequester;
import com.ffcs.network.connect.okhttp.client.listener.OkResponseListener;
import com.ffcs.network.connect.okhttp.request.OkRequestCall;
import com.ffcs.network.connect.okhttp.request.OkRequestUtils;
import com.ffcs.network.connect.okhttp.request.PostFormBuilder;
import com.ffcs.network.connect.okhttp.request.ReqeustBuilder;
import com.google.gson.Gson;

import java.util.concurrent.ExecutionException;


/**
 * Created by kinglong on 14-10-17.
 */
public abstract class BaseRequest<T>  {
    private final String TAG = BaseRequest.class.getSimpleName();
    protected ResponseListener mResponsLisetener;
    protected int mTag;
    protected Context mContext;
    protected PostFormBuilder mReqWrapper;
    protected OkRequestCall mRequestCall;

    protected boolean isCanceledAfterActFinish;        //activity关闭是否也取消请求,默认为true
    protected String url;
    private ReqeustBuilder reqeustBuilder;
    private boolean isPost;
    private OkRequestCall requestCall;


    public BaseRequest(Context context, int tag, ResponseListener listener, String url) {
        mContext = context;
        mTag = tag;
        mResponsLisetener = listener;
        isCanceledAfterActFinish = true;
        this.url=url;
//        mReqWrapper= OkRequestUtils.post().url(url);
        reqeustBuilder = OkRequestUtils.get().url(url);
        reqeustBuilder.tag(mContext);
        Log.d("url",url);
//        mReqWrapper.tag(mContext);



    }

    public BaseRequest(Context context, int tag, ResponseListener listener, String url,boolean isPost) {
        mContext = context;
        mTag = tag;
        mResponsLisetener = listener;
        isCanceledAfterActFinish = true;
        this.url=url;
        this.isPost=isPost;
        if (isPost){
            mReqWrapper= OkRequestUtils.post().url(url);
        }else {
            reqeustBuilder = OkRequestUtils.get().url(url);
        }


        mReqWrapper.tag(mContext);



    }


    protected void executeRequest() {
        if (isPost){
            if (TextUtils.isEmpty(mReqWrapper.getUrl())) {
                Log.e(TAG, "your request url cannot empty ");
                onFailure(CustomerError.getServerError(), mTag);
                return;
            }
            requestCall = mReqWrapper.build();
        }else {
            if (TextUtils.isEmpty(reqeustBuilder.getUrl())) {
                Log.e(TAG, "your request url cannot empty ");
                onFailure(CustomerError.getServerError(), mTag);
                return;
            }
           requestCall=reqeustBuilder.build();
        }

//
        Log.d(TAG, requestCall.getOkHttpRequest().toString());
        OkRequester.getInstance().enqueue(requestCall, getResponseListener());
    }


    public void cancel(){
        OkRequester.getInstance().remove(mRequestCall);
        //OkRequest.getInstance().remove(mReqWrapper);
    }

    public abstract void sendRequest();
    public abstract Class<T> getResponseClass();


    public void onSuccess(T response, int tag) {     //如果有的请求需要特殊处理的可以重写这两个方法
        mResponsLisetener.onRequestSuccess(response, tag);
    }

    public void onFailure(CustomerError error, int tag) {
        mResponsLisetener.onRequestFailure(error, tag);
    }


    protected OkResponseListener getResponseListener() {
        return new OkResponseListener() {
            @Override
            public void onReqSuccess(String value) {

                Log.d(TAG, "response fuccess response= " + value);
                if (isCanceledAfterActFinish && null != mContext && mContext instanceof Activity && ((Activity) mContext).isFinishing()) {
                    Log.d(TAG, "onResponse isCanceledAfterActFinish activity is finishing ");
                } else if (null != value) {
                    try{
                        Gson gson = new Gson();
                        //json长不规范，暂时这样
                        T t = gson.fromJson(value, getResponseClass());
                        onSuccess(t, mTag);

                    }catch (Exception e){
                        onFailure(CustomerError.getDataError(), mTag);
                    }

                } else {
                    onFailure(CustomerError.getDataError(), mTag);
                }

            }

            @Override
            public void onReqFailure(CustomerError error) {
                try {
                    if (isCanceledAfterActFinish && null != mContext && mContext instanceof Activity && ((Activity) mContext).isFinishing()) {
                        Log.d(TAG, "onErrorResponse isCanceledAfterActFinish activity is finishing ");
                    } else {
                        onFailure(error, mTag);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(CustomerError.getUnKnownError(), mTag);
                }
            }

        };
    }


    public boolean isCanceledAfterActFinish() {
        return isCanceledAfterActFinish;
    }

    public void setCanceledAfterActFinish(boolean isCanceledAfterActFinish) {
        this.isCanceledAfterActFinish = isCanceledAfterActFinish;
    }
}
